package com.pengliu.config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.pengliu.common.bean.SysAuth;
import com.pengliu.common.bean.SysRole;
import com.pengliu.common.bean.SysUser;
import com.pengliu.config.security.SecurityDetails;

public class BaseController {
	
	@Autowired
	public HttpServletRequest request;
	
	@Autowired
	public HttpServletResponse response;
	
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return getModelAndView(null);
	}
	
	public ModelAndView getModelAndView(String viewName){
		if(viewName.substring(0,1).equals("/")) {
			viewName = viewName.substring(1);
		}
		return new ModelAndView(viewName);
	}
	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年9月29日
	 * desc: 获取当前登陆信息
	 * @return
	 */
	public static SysUser getCurrentSysUser() {
		
		SysUser userDetails = null ;
		if (SecurityContextHolder.getContext().getAuthentication() != null) {
			userDetails = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		}
		return userDetails;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月10日
	 * desc: 获取当前角色信息
	 * @return
	 */
	public SysRole getCurrentSysRole() {
		SysRole sysRole = null;
		if (SecurityContextHolder.getContext().getAuthentication() != null) {
			SecurityDetails securityDetails = (SecurityDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			sysRole = securityDetails.getSysRole();
		}
		return sysRole;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月10日
	 * desc: 获取当前权限集合
	 * @return
	 */
	public List<SysAuth> getCurrentSysAuth(){
		List<SysAuth> listSysAuth = null;
		if (SecurityContextHolder.getContext().getAuthentication() != null) {
			SecurityDetails securityDetails = (SecurityDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			listSysAuth = securityDetails.getListSysAuth();
		}
		return listSysAuth;
	}
}
